/* eslint-disable no-unused-vars */
/* eslint-disable no-debugger */
import axios from 'axios';
import QS from 'qs';
import { baseUrl } from "../config/envconfig";
import { message, Modal } from 'antd';
import { getStore } from '@/utils/commons';

const axiosInstance = axios.create({
    baseUrl: baseUrl,
    timeout: 30000,
});

axiosInstance.interceptors.request.use(config => {
    config.headers['deviceId'] = 'web'
    if (getStore('token')) {
        config.headers['Authorization'] = 'Bearer ' + getStore('token')
    } else {
        config.headers['Authorization'] = 1
    }
    return config
}, error => {
    return Promise.reject(error)
});

axiosInstance.interceptors.response.use(response => {
    const res = response.data;
    if (res.code == 200) {
        return res
    } else {
        message.error(res.code + ':' + res.message)
        return Promise.resolve(res);
    }
}, error => {
    const err = error.response;
    console.log(error.response)
    if (err.status === 401) {
        Modal.warning({
            title: '温馨提示',
            content: '权限您已经登录超时，请回首页重新登录',
            okText: '登录',
            onOk() {
                $get('/user/loginout').then(res => {
                    window.location.href = '/login'
                })
            }
        });
    } else if (err.status === 504) {
        message.error(err.statusText, 3)
    } else {
        message.error(err.data.message, 3)
    }
    return Promise.reject(err.data);
});

const _option = {
    headers: null,
    withCredentials: true,//是否携带cookie 发起请求
    validateStatus: (status) => {
        return status >= 200 && status < 300
    }
};

export function $post(url, data = {}, contentType) {
    let ct = contentType || 'application/json;charset=UTF-8'
    var opt = Object.assign({}, _option, { data: data, headers: { 'Content-Type': ct } });
    return new Promise((resolve, reject) => {
        axiosInstance.request({
            ...opt,
            method: 'POST',
            url: baseUrl + url
        }).then((res) => {
            resolve(res)
        })
    })
}

export function $get(url, data = null, contentType) {
    let ct = contentType || 'application/x-www-form-urlencoded;charset=UTF-8'
    var opt = Object.assign({}, _option, { params: data, headers: { 'Content-Type': ct } });
    return new Promise((resolve, reject) => {
        axiosInstance.request({
            ...opt,
            method: 'GET',
            url: baseUrl + url
        }).then(res => {
            resolve(res)
        })
    })
}
